/**
 * [LupMisNotAllowedSync]
 * 本代码为系统自动生成代码，请根据自己业务进行修改;
 * 生成时间 2022-02-02 11:18:21;
 * 版权所有 2020-2022 lizhongwen，并保留所有权利;
 * 说明: 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用；不允许对程序代码以任何形式任何目的的再发布;
 * 作者: 中文Lee;
 * 作者主页: http://www.lizhongwen.com;
 * 邮箱: 360811363@qq.com;
 * QQ: 360811363;
 */

layui.use(['layer', 'table', 'form'], function() {
    ajaxStart();
    //统一给ajax请求加header参数
    ajaxSend();
    //截获ajax参数
    ajaxSetup();
});
var showRenameBtn = true;
var showRemoveBtn = true;
//这里引用一下，否则不生效
$(document).ajaxSend(function(event, jqxhr, settings) {
    jqxhr.setRequestHeader("accessuid", localStorage.getItem("accessuid"));
    jqxhr.setRequestHeader("accesstoken", localStorage.getItem("accesstoken"));
    ajaxStart();
});
var setting = {
    async: {
        enable: true,
        contentType: "application/json;charset=utf-8",
        headers: {
            'accessuid': localStorage.getItem("accessuid"),
            'accesstoken': localStorage.getItem("accesstoken")
        },
        type: "post",
        dataType: "json",
        autoParam: ["id", "name"],
        url: base_gateway + "sys/org/lists",
        dataFilter: filter
    },
    view: {
        expandSpeed: "1",
        addHoverDom: addHoverDom,
        removeHoverDom: removeHoverDom,
        showLine: true,
        showIcon: true,
        showTitle: true,
        selectedMulti: false
    },
    edit: {
        drag: {
            prev: false,
            inner: false,
            next: false
        },
        enable: true,
        showRenameBtn: showRenameBtn,
        showRemoveBtn: showRemoveBtn
    },
    data: {
        simpleData: {
            enable: true
        }
    },
    callback: {
        beforeRemove: beforeRemove,
        beforeRename: beforeRename,
        beforeClick: beforeClick,
        onClick: onClick,
        onAsyncSuccess: zTreeOnAsyncSuccess, // 异步加载正常结束的事件回调函数
    }
};
//节点移动
function zTreeMoveNode(moveType) {
    var targetNode;
    var treeObj = $.fn.zTree.getZTreeObj("treeDemo");
    var treeNode = treeObj.getSelectedNodes();
    if (treeNode.length == 0) {
        layer.msg("请选择要移动的节点");
        return false;
    }
    if (moveType == 'prev') {
        if (treeNode.length > 0) {
            targetNode = treeNode[0].getPreNode();
        }
    } else {
        if (treeNode.length > 0) {
            targetNode = treeNode[0].getNextNode();
        }
    }
    if (targetNode == null || targetNode == "" || targetNode == "null") {
        layer.msg("不能再移动啦！");
        return false;
    }
    var isSilent = false;

    var loading = layer.load(2, {
        shade: [0.1, '#393D49'],
    });
    var data = {
        id: treeNode[0].id,
        target_id: targetNode.id,
        move_type: moveType
    };
    request(base_gateway + "sys/org/move", data, function(ret) {
        layer.close(loading);
        if (ret.code == 200) {
            treeObj.moveNode(targetNode, treeNode[0], moveType, isSilent);
        } else {
            layer.msg(ret.msg);
        }
    });


}
//用于捕获异步加载正常结束的事件回调函数
function zTreeOnAsyncSuccess(event, treeId, treeNode, msg) {

    var ret = msg;
    if (ret.code == 401) {
        localStorage.setItem("accesstoken", null);
        localStorage.setItem("accessuid", null);
        layer.alert(ret.msg, {
            icon: 1,
            closeBtn: 0
        }, function(index) {
            //关闭弹窗
            layer.close(index);
            window.location.href = project_path + "login.html";
        });
    } else if (ret.code == 403) {
        layer.msg(ret.msg);
        return false;
    }

    var treeObj = $.fn.zTree.getZTreeObj(treeId);
    var nodes = treeObj.getNodes();
    //默认展开前3个
    treeObj.expandAll(true);
    for (var i = 0; i < nodes.length; i++) {
        // treeObj.expandNode(nodes[i], true, false, false); //默认展开第一级节点
    }


}

function filter(treeId, parentNode, childNodes) {
    if (!childNodes) return null;
    var i = 0,
        l = childNodes.length;
    for (; i < l; i++) {
        childNodes[i].name = childNodes[i].name.replace(/\.n/g, '.');
    }
    return childNodes;
}

function beforeClick(treeId, treeNode, clickFlag) {
    onClick(null, treeId, treeNode, clickFlag);
}
//目录点击事件
function onClick(event, treeId, treeNode, clickFlag) {
    //这里还是需要重新调用一下接口吧
    request(base_gateway + "sys/org/query", { id: treeNode.id }, function(ret) {
        if (ret.code == 200) {
            $("#org_name").text(ret.data.name);
            $("#org_name").css("background-color", "#01c924");
            $("input[name='id']").val(ret.data.id);
            $("input[name='pid']").val(ret.data.pid);
            $("input[name='name']").val(ret.data.name);
            // $("input[name='status']").val(ret.data.status);
            $("input[name='leader']").val(ret.data.leader);
            $("input[name='phone']").val(ret.data.phone);
            $("input[name='email']").val(ret.data.email);
            $("input[name='address']").val(ret.data.address);
            $("textarea[name='remarks']").val(ret.data.remarks);

            if (ret.data.status == 1) {
                $("input[name='status']").attr("checked", true);
            } else {
                $("input[name='status']").removeAttr("checked");
            }
            layui.form.render(null, null);
        } else {
            layer.msg(ret.msg, {
                shade: [0.1, '#393D49'],
                time: 1500,
                icon: 5
            });
        }
    });

}
//删除目录
function beforeRemove(treeId, treeNode) {
    var id = treeNode.id;
    var zTree = $.fn.zTree.getZTreeObj("treeDemo");
    zTree.selectNode(treeNode);
    layer.confirm('确定要删除该机构信息吗？', function(index) {
        request(base_gateway + "sys/org/del", { id: treeNode.id }, function(ret) {
            if (ret.code == 200) {
                //将表单值置空
                $("#org_name").text("未选择机构");
                $("#org_name").css("background-color", "#999999");
                $("input[name='pid']").val("0");
                $("input[name='id']").val("0");
                $("input[name='name']").val("");
                $("input[name='status']").val(1);
                $("input[name='leader']").val("");
                $("input[name='phone']").val("");
                $("input[name='email']").val("");
                $("input[name='address']").val("");
                $("textarea[name='remarks']").val("");
                layer.msg(ret.msg, {
                    shade: [0.1, '#393D49'],
                    time: 1500,
                    icon: 6
                });
                zTree.removeNode(zTree.getSelectedNodes()[0]);
            } else {
                layer.msg(ret.msg, {
                    shade: [0.1, '#393D49'],
                    time: 1500,
                    icon: 5
                });
            }
            layer.close(index);
        });

    });
    return false;
}

//修改名称
function beforeRename(treeId, treeNode, newName) {

    if (newName.length == 0) {
        var zTree = $.fn.zTree.getZTreeObj("treeDemo");
        zTree.cancelEditName();
        layer.msg('名称不能为空');
        return false;
    } else {

        request(base_gateway + "sys/org/editName", {
            id: treeNode.id,
            name: newName
        }, function(ret) {
            onClick(null, treeId, treeNode, true);
            //var zTree = $.fn.zTree.getZTreeObj("treeDemo");
            //zTree.addNodes(treeNode, {id:ret.nodesId, pId:treeNode.id, name:ret.nodesName})
        });
        return true;
    }

}

function addHoverDom(treeId, treeNode) {
    var sObj = $("#" + treeNode.tId + "_span");
    if (treeNode.editNameFlag || $("#addBtn_" + treeNode.tId).length > 0) return;
    var addStr = "<span class='button add' id='addBtn_" + treeNode.tId + "' title='add node' onfocus='this.blur();'></span>";
    sObj.after(addStr);
    var btn = $("#addBtn_" + treeNode.tId);
    if (btn) btn.bind("click", function() {
        createNewNodes(treeNode, treeNode.id);
    });
};
//创建新目录
function createNewNodes(treeNode, pId) {
    //type = 0 开头创建，-1末尾创建
    layer.confirm('选择创建的位置？', {
        btn: ['开头创建', '末尾创建', '取消'],
        btn3: function(index, layero) {
            layer.close(index);
        }
    }, function(index, layero) {
        //开头创建
        var position = 0;
        request(base_gateway + "sys/org/add", {
            name: '（请重命名）',
            pid: pId,
            position: position
        }, function(ret) {
            if (ret.code == 200) {
                var zTree = $.fn.zTree.getZTreeObj("treeDemo");
                zTree.addNodes(treeNode, position, {
                    id: ret.data.id,
                    pId: ret.data.pid,
                    name: ret.data.name
                });
            } else {
                layer.msg(ret.msg);
            }
            layer.close(index);
        });
        return false;
    }, function(index) {
        //末尾创建
        var position = -1;
        request(base_gateway + "sys/org/add", {
            name: '（请重命名）',
            pid: pId,
            position: position
        }, function(ret) {
            if (ret.code == 200) {
                var zTree = $.fn.zTree.getZTreeObj("treeDemo");
                zTree.addNodes(treeNode, position, {
                    id: ret.data.id,
                    pId: ret.data.pid,
                    name: ret.data.name
                });
            } else {
                layer.msg(ret.msg);
            }
            layer.close(index);
        });
        return false;
    });
    return false;
}

function removeHoverDom(treeId, treeNode) {
    $("#addBtn_" + treeNode.tId).unbind().remove();
};
var treeDemoObj;
$(document).ready(function() {
    treeDemoObj = $.fn.zTree.init($("#treeDemo"), setting);
});

//保存数据
function saveData() {
    var dataJson = formToJson($("form").serialize());
    if (dataJson.status && dataJson.status == 'on') {
        dataJson.status = 1;
    } else {
        dataJson.status = -1;
    }
    var id = $("input[name='id']").val();
    if (id == "0" || id == "") {
        layer.msg("请选择左侧机构", {
            shade: [0.1, '#393D49'],
            time: 1500,
            icon: 5
        });
        return false;
    }
    request(base_gateway + "sys/org/edit", dataJson, function(ret) {
        if (ret.code == 200) {
            layer.msg(ret.msg, {
                shade: [0.1, '#393D49'],
                time: 1500,
                icon: 6
            });
        } else {
            layer.msg(ret.msg, {
                shade: [0.1, '#393D49'],
                time: 1500,
                icon: 5
            });
        }
    });
    return false;
}

$(function() {

    var windowH = $(window).height();
    if (windowH <= 300) {
        windowH = 300;
    }
    $("#right").css("height", (windowH - 125) + "px");
    $("#left").css("height", (windowH - 125) + "px");
    $("#treeDemo").css("height", (windowH - 135) + "px");
    $(window).resize(function() { //当浏览器大小变化时
        var windowH = $(window).height();
        if (windowH <= 300) {
            windowH = 300;
        }
        $("#right").css("height", (windowH - 125) + "px");
        $("#left").css("height", (windowH - 125) + "px");
        $("#treeDemo").css("height", (windowH - 135) + "px");
    });
});